#!/bin/sh

NAVG1=1
NAVG2=5
TAVGSWITCH=200


GNUPLOTFILE=/tmp/width.gnuplot
#echo "set terminal x11 enhanced" > $GNUPLOTFILE
echo "set terminal post color eps enhanced font \"Helvetica,18\"" > $GNUPLOTFILE
echo "set output 'width-k.eps'" >>  $GNUPLOTFILE
echo "set size 1,2; set lmargin 9; set rmargin 9;" >> $GNUPLOTFILE
#echo "set xlabel 't'" >> $GNUPLOTFILE
#echo "set grid'" >> $GNUPLOTFILE
echo "set multiplot layout 2,1" >> $GNUPLOTFILE

### WIDTH plotting

echo "set ylabel 'width' offset 1" >> $GNUPLOTFILE
echo "unset xtics ; set xtics 0,100,900 ; set xlabel 't' ;" >> $GNUPLOTFILE
echo "set size 1,1; set origin 0,1;" >> $GNUPLOTFILE
echo "set border 3 ; set tmargin 1; set bmargin 0; " >> $GNUPLOTFILE
echo -n "plot [0:*][0:*] " >> $GNUPLOTFILE

FIRST=yes

for f in `ls -v "$@"` ; do
	sizefile=${f/log/size}
	grep xsize "$f" | sed 's/[a-z]\+=//g' | tr -d ':' | \
		 LANG=C awk -v N1=$NAVG1 -v N2=$NAVG2 -v T=$TAVGSWITCH \
		 'BEGIN { i=0; tsum=0.0; sum=0.0; vsum=0.0; } \
			 { if ( $1 < T ) N=N1 ; else N=N2 ; \
			  tsum+=$1 ; sum+=$4; vsum+=$5 ; i+=1 ; \
			  if ( i == N ) { \
				  print tsum/N, sum/N, vsum/N ; \
				  tsum = sum = vsum = 0.0 ; i=0 ; \
			  } \
		  }' > ${sizefile}
#		 awk '{print $1,$4,$5;}' > ${sizefile}
	tag=`echo $f | cut -d '_' -f 3 ` ;
	echo $tag ; 
	if [ "x$FIRST" == "xyes" ] ; then
		FIRST=no ;
	else
		echo -n "," >> $GNUPLOTFILE ;
	fi
	echo -n "'$sizefile' u 1:2 every 1 w l t '$tag' " \
		>> $GNUPLOTFILE
done
echo >> $GNUPLOTFILE

## plotting anaerobic fraction

echo "set size 1,1; " >> $GNUPLOTFILE
echo "set border 13 ; unset key ; " >> $GNUPLOTFILE
echo "unset ylabel ; set y2label 'anaerobic fraction, %' ; " >> $GNUPLOTFILE
echo "set ytics 0,10,90 ; set y2tics 0,10,100 mirror " >> $GNUPLOTFILE
echo "set xtics 0,100,1000; set xlabel 't'" >> $GNUPLOTFILE
echo "set x2tics 1000,100,1001 ; " >> $GNUPLOTFILE
echo "set tmargin 0; set bmargin 3;" >> $GNUPLOTFILE

echo -n "plot [0:*][0:100] " >> $GNUPLOTFILE

FIRST=yes

for f in `ls -v "$@"` ; do
	massfile=${f/log/mass}
	grep M_1 "$f" | tr -d 't:=' | \
		 LANG=C awk '{print $1,100*$5/($3+$5);}' > ${massfile}
	tag=`echo $f | cut -d '_' -f 3 ` ;
	echo $tag ; 
	if [ "x$FIRST" == "xyes" ] ; then
		FIRST=no ;
	else
		echo -n "," >> $GNUPLOTFILE ;
	fi
	echo -n "'$massfile' u 1:2 every 1 w l t '$tag' " \
		>> $GNUPLOTFILE
done
echo >> $GNUPLOTFILE

echo "unset multiplot" >> $GNUPLOTFILE

gnuplot -persist - < $GNUPLOTFILE

